package com.onlyxiahui.common.utils.base.security;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * Description <br>
 * Date 2021-04-25 18:09:54<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class CipherUtil {

	public static Cipher getCipher(int mode, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(key.getAlgorithm());
			cipher.init(mode, key);
		} catch (NoSuchAlgorithmException e) {
			final Throwable cause = e.getCause();
			if (cause instanceof NoSuchAlgorithmException) {
				// 在Linux下，未引入BC库可能会导致RSA/ECB/PKCS1Padding算法无法找到，此时使用默认算法
//				this.algorithm = AsymmetricAlgorithm.RSA.getValue();
//				super.initCipher();
			}
			throw e;
		}
		return cipher;
	}

	public static byte[] doFinalWithBlock(Cipher cipher, byte[] data, int maxBlockSize) throws IllegalBlockSizeException, BadPaddingException, IOException {
		final int dataLength = data.length;
		final ByteArrayOutputStream out = new ByteArrayOutputStream();

		int offSet = 0;
		// 剩余长度
		int remainLength = dataLength;
		int blockSize;
		// 对数据分段处理
		while (remainLength > 0) {
			blockSize = Math.min(remainLength, maxBlockSize);
			out.write(cipher.doFinal(data, offSet, blockSize));

			offSet += blockSize;
			remainLength = dataLength - offSet;
		}

		return out.toByteArray();
	}
}
